<?php
namespace admin\models\user;

use Yii;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            /* if (!$user || !$user->validatePassword($this->password)) {
             $this->addError($attribute, 'Incorrect username or password.');
             } */
            
            // 用户输入的原始登录密码加密处理
            if(!empty($user)) {
                $this->password = User::generateMd5Password($this->password);
                if (!$user->validatePassword($this->password)) {
                    $this->addError($attribute, 'Incorrect username or password.');
                }
            }else {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            //return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
            
            /*
             * 根据rule()方法规则进行登录数据校验,如validatePassword校验密码
             * 登录成功，返回登录用户信息model
             */
            $user_model = $this->getUser();
            $this->saveAccessTokenToUser($user_model->login_token);
            $login_res = Yii::$app->user->login($user_model, $this->rememberMe ? 3600 * 24 * 30 : 0);
            if ($login_res == false) {
                return false;
            }
            return $user_model;
        }
        
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
    
    /**
     * @huqq
     * 登录校验成功后，读取user表的token，检查是否有效；
     * 如果token失效或为空，则重新生成token，保存到DB; 如果token有效，则直接使用user的token
     */
    private function saveAccessTokenToUser($token)
    {
        if (!User::isPasswordResetTokenValid($token)) {
            // access_token校验失败，重新生成
            $this->_user->generatePasswordResetToken();
            // 更新user的access_token
            $this->_user->save(false);
        }
        return true;
    }
}
